import logging

from flask import Blueprint, jsonify, request

from mysql_tool.mysql_tool import MySQLTool

material_bp = Blueprint('material', __name__)

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


def get_material(mysql_tool, reel_id):
    """根据流水号查询对应的物料信息"""
    logger.info(f"查询对应的物料信息: {reel_id}")

    # 使用参数化查询防止SQL注入
    material_sql = """
                   SELECT id         AS id,
                          CreateTime AS createTime,
                          ReelID     AS reelId,
                          Qty        AS quantity,
                          WoCode     AS woCode
                   FROM sfcdatmes_material_ready_log
                   WHERE ReelID = %s
                   ORDER BY CreateTime Desc
                   LIMIT 1 \
                   """

    logger.info(f"执行的SQL语句: {material_sql}")

    # 执行查询
    results = mysql_tool.execute_query(material_sql, (reel_id,))

    # 处理结果，直接返回单个对象
    if results and len(results) > 0:
        row = results[0]
        item = {
            "id": row[0],
            "createTime": row[1],
            "reelId": row[2],
            "quantity": row[3],
            "woCode": row[4]
        }
        logger.info(f"查询到物料记录: {item}")
        return item

    logger.info("未查询到物料记录")
    return None


@material_bp.route('/query_material', methods=['POST'])
def query_smt():
    """通过流水号查询对应的物料信息"""
    try:
        # 获取请求中的JSON数据
        request_data = request.get_json()
        if not request_data:
            return jsonify({"success": False, "message": "请求数据不能为空"}), 400

        # 获取流水号
        reel_id = request_data.get('reelId')

        if not reel_id:
            return jsonify({"success": False, "message": "唯一码不能为空"}), 400

        logger.info(f"收到查询请求，唯一码: {reel_id}")

        # 创建MySQL工具实例
        mysql_tool = MySQLTool('172.27.32.57', 'root', 'zc123456', 'a50', '9988')

        # 确保连接数据库
        if not mysql_tool.connect():
            return jsonify({"success": False, "message": "数据库连接失败"}), 500

        try:
            # 查询物料信息
            material_data = get_material(mysql_tool, reel_id)

            if material_data is None:
                return jsonify({
                    "success": False,
                    "message": "未找到相关物料信息"
                }), 404

            # 返回结果，直接返回对象而非列表
            return jsonify({
                "success": True,
                "data": material_data
            })

        finally:
            # 确保断开数据库连接
            mysql_tool.disconnect()

    except Exception as e:
        logger.error(f"查询物料信息失败: {str(e)}")
        return jsonify({
            "success": False,
            "message": f"查询失败: {str(e)}"
        }), 500
